package com.ct.rbac.repository.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ct.rbac.convert.SysUserConvertDOToModel;
import com.ct.rbac.mapper.SysUserMapper;
import com.ct.rbac.model.SysUserModel;
import com.ct.rbac.orm.SysUserDO;
import com.ct.rbac.orm.SysUserRolesDO;
import com.ct.rbac.repository.ISysUserRespontory;
import com.ct.rbac.repository.ISysUserRolesRespontory;
import com.ct.repository.commons.BaseServiceImpl;
import com.ct.repository.commons.PageUtils;
import com.ct.utils.pwd.MD5Util;
import com.ct.utils.threadlocal.UserThreadLocal;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Repository
public class SysUserRespontoryImpl extends BaseServiceImpl<SysUserMapper, SysUserDO> implements ISysUserRespontory {

    @Autowired
    private SysUserConvertDOToModel sysUserConvertDOToModel;
    @Autowired
    private ISysUserRolesRespontory sysUserRolesRespontory;




    /**
     * 根据系统id查询用户列表信息并分页
     */
    @Override
    public PageUtils<SysUserModel> findUserListBySystemId(Integer pageNo, Integer pageSize, Integer status, Integer isDeleted, String keywords){
        Long systemId = UserThreadLocal.get().getSystemId();
        Page<SysUserDO> page = new Page<>(pageNo,pageSize);
        QueryWrapper<SysUserDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.apply("t1.id = t2.user_id");
        queryWrapper.eq("t2.system_id",systemId);
        queryWrapper.ne("t1.id",1);
        queryWrapper.eq(Objects.nonNull(isDeleted), "t1.is_deleted", isDeleted);
        queryWrapper.eq(Objects.nonNull(status),"t1.status", status);
        queryWrapper.and(StringUtils.isNoneEmpty(keywords), c -> {
            c.like("t1.username", keywords).or()
                    .like("t1.account", keywords).or()
                    .like("t1.phone", keywords);
        });

        Page<SysUserDO> doPage = this.baseMapper.findUserListBySystemId(page, queryWrapper);
        return tranferPageUtilsBo(doPage, SysUserModel.class);
    }

    /**
     * 查询用户列表信息
     *
     * @param pageNo
     * @param pageSize
     * @param status
     * @param keyword
     * @return
     */
    @Override
    public PageUtils<SysUserModel> findPage(Integer pageNo, Integer pageSize, Integer status, Integer isDeleted, String keyword) {
        Page<SysUserDO> page = new Page<>(pageNo, pageSize);
        LambdaQueryWrapper<SysUserDO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        // 按需加载
        //lambdaQueryWrapper.select(SysUserDO::getId,SysUserDO::getAccount,.....);
        // 排除方式
        //lambdaQueryWrapper.select(SysUserDO.class,c->(!c.getColumn().equalsIgnoreCase("email") && !c.getColumn().equalsIgnoreCase("avatar")));
        lambdaQueryWrapper.eq(Objects.nonNull(status), SysUserDO::getStatus, status);
        lambdaQueryWrapper.eq(Objects.nonNull(isDeleted), SysUserDO::getIsDeleted, isDeleted);
        lambdaQueryWrapper.and(StringUtils.isNoneEmpty(keyword), c -> {
            c.like(SysUserDO::getUsername, keyword).or()
                    .like(SysUserDO::getAccount, keyword).or()
                    .like(SysUserDO::getPhone, keyword);

        });
        lambdaQueryWrapper.orderByAsc(SysUserDO::getCreateTime);
        Page<SysUserDO> doPage = this.page(page, lambdaQueryWrapper);
        return tranferPageUtilsBo(doPage, SysUserModel.class);
    }

    @Override
    public SysUserModel selectBySysUserByAccount(String account) {
        LambdaQueryWrapper<SysUserDO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SysUserDO::getAccount, account);
        SysUserDO sysUserDO = this.getOne(lambdaQueryWrapper);
        return sysUserConvertDOToModel.convert(sysUserDO);
    }

    @Override
    public SysUserModel selectBySysUserById(Long id) {
        SysUserDO sysUserDO = this.getById(id);
        return sysUserConvertDOToModel.convert(sysUserDO);
    }

    /**
     * 修改密码
     *
     * @return
     */
    @Override
    public Boolean updatePassword(Long userId, String newPassword) {
        SysUserDO sysUserDO = this.getById(userId);
        if (Objects.nonNull(sysUserDO)) {
            sysUserDO.setId(userId);
            sysUserDO.setPassword(MD5Util.md5slat(newPassword, sysUserDO.getSlat()));
            return this.updateById(sysUserDO);
        } else {
            return false;
        }
    }


    /**
     * 绑定角色
     *
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean bindRolesSysUsers(Long userId, String roleIds) {
        // 1：根据用户id把之前的角色信息删除
        LambdaQueryWrapper<SysUserRolesDO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SysUserRolesDO::getUserId, userId);
        sysUserRolesRespontory.remove(lambdaQueryWrapper);
        // 2: 然后在重新绑定新的角色
        List<SysUserRolesDO> sysUserRolesDOS = Arrays.asList(roleIds.split(",")).stream().map(c -> {
            SysUserRolesDO sysUserRolesDO = new SysUserRolesDO();
            sysUserRolesDO.setUserId(userId);
            sysUserRolesDO.setRoleId(Long.parseLong(c));
            return sysUserRolesDO;
        }).collect(Collectors.toList());
        return sysUserRolesRespontory.saveBatch(sysUserRolesDOS);
    }
}
